package com.samphanie.auiu.generator.controller;

import com.samphanie.auiu.common.utils.ApiResponse;
import com.samphanie.auiu.generator.entity.GenTable;
import com.samphanie.auiu.generator.entity.GenTableColumn;
import com.samphanie.auiu.generator.service.IGenTableColumnService;
import com.samphanie.auiu.generator.service.IGenTableService;
import com.samphanie.auiu.mbg.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Api(tags = "代码生成")
@RestController
@RequestMapping("/tools")
@RequiredArgsConstructor
public class GenController {

    private final IGenTableService genTableService;

    private final IGenTableColumnService genTableColumnService;


    @ApiOperation("查询代码生成列表")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataTypeClass = Integer.class, paramType = "query")
    })
    public ApiResponse<?> genList(GenTable genTable,
                                  @RequestParam(name = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                  @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize
    ) {
        PageUtils.startPage(pageNum, pageSize);
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        return ApiResponse.success(new PageUtils(list));
    }

    @ApiOperation("修改代码生成业务")
    @GetMapping(value = "/{tableId}")
    public ApiResponse<?> getInfo(@PathVariable Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("list", list);
        map.put("tables", tables);
        return ApiResponse.success(map);
    }

    @ApiOperation("查询数据库列表")
    @GetMapping("/db/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataTypeClass = Integer.class, paramType = "query")
    })
    public ApiResponse<?> dataList(GenTable genTable,
                                   @RequestParam(name = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                   @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize
    ) {
        PageUtils.startPage(pageNum, pageSize);
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        return ApiResponse.success(new PageUtils(list));
    }

    @ApiOperation("查询数据表字段列表")
    @GetMapping(value = "/column/{tableId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableId", value = "表ID", dataTypeClass = Long.class, paramType = "path"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataTypeClass = Integer.class, paramType = "query")
    })
    public ApiResponse<?> columnList(@PathVariable Long tableId,
                                     @RequestParam(name = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                     @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize
    ) {
        PageUtils.startPage(pageNum, pageSize);
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        return ApiResponse.success(new PageUtils(list));
    }

    @ApiOperation("导入表结构（保存）")
    @PostMapping("/importTable")
    public ApiResponse<?> importTableSave(@RequestBody String[] tables) {
        // String[] tableNames = tables.split(",");
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tables);
        genTableService.importGenTable(tableList);
        return ApiResponse.success();
    }

    @ApiOperation("修改保存代码生成业务")
    @PutMapping("/editSave")
    public ApiResponse<?> editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return ApiResponse.success();
    }

    @ApiOperation("删除代码生成")
    @DeleteMapping("/remove")
    public ApiResponse<?> remove(@RequestBody Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return ApiResponse.success();
    }

    @ApiOperation("预览代码")
    @GetMapping("/preview/{tableId}")
    public ApiResponse<?> preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return ApiResponse.success(dataMap);
    }

    @ApiOperation("生成代码（下载方式）")
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    @ApiOperation("生成代码（自定义路径）")
    @GetMapping("/genCode/{tableName}")
    public ApiResponse<?> genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return ApiResponse.success();
    }

    @ApiOperation("同步数据库")
    @GetMapping("/synchDb/{tableName}")
    public ApiResponse<?> synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return ApiResponse.success();
    }

    @ApiOperation("批量生成代码")
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = tables.trim().split(",");
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
//        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"auiu.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
